package com.esun.cheetah.view.news;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import com.esun.cheetah.R;
import com.esun.cheetah.network.ConnectionChangeReceiver;
import com.esun.util.log.EDebug;

public class NewsContent extends Activity implements OnClickListener {
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 404) {// 主页不存在
				// 载入本地assets文件夹下面的错误提示页面404.html
				web.loadUrl("file:///android_asset/404.html");
			} else {
				web.loadUrl(url);
			}
		}
	};
//	private Intent intent;
	private Intent intentToSportteryFootball;
	private Bundle bundleToSportteryFootbal;
	private View progress;
	private WebView web;
//	private LinearLayout llNoLine;
	private Button btnNoLine;
	private String url;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_content);
		Intent intent = getIntent();
		url = intent.getStringExtra("url");

		initUI();

		qQiu();

	}

	public void initUI() {
		((Button) this.findViewById(R.id.news_web_act_btn_goBack))
				.setOnClickListener(this);
		((Button) this.findViewById(R.id.news_web_act_btn_gouc))
				.setOnClickListener(this);
		progress = (View) this.findViewById(R.id.news_web_act_progress);
		btnNoLine = (Button) findViewById(R.id.news_web_btn_norecord);
		btnNoLine.setOnClickListener(this);
//		llNoLine = (LinearLayout) this
//				.findViewById(R.id.news_web_act_lv_title1);
		web = (WebView) this.findViewById(R.id.news_web_web);
	}

	public void qQiu() {
		web.getSettings().setJavaScriptEnabled(true);
		web.setVerticalScrollBarEnabled(false);
		web.setHorizontalScrollBarEnabled(false);
		web.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				progress.setVisibility(View.GONE);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				progress.setVisibility(View.VISIBLE);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView web, String url) {
				if (url.startsWith("http://") && getRespStatus(url) == 404) {
					web.stopLoading();
					// 载入本地assets文件夹下面的错误提示页面404.html
					web.loadDataWithBaseURL("file:///android_asset/", null,
							"text/html", "utf-8", null);

					web.loadUrl("file:///android_asset/404.html");
				} else {
					web.loadUrl(url);
				}
				return true;
			}
			// @Override
			// public void onReceivedError(WebView view, int errorCode,
			// String description, String failingUrl) {
			// Log.v("message", "error");
			// super.onReceivedError(view, errorCode, description, failingUrl);
			// }
		});
		web.loadUrl(url);

		new Thread(new Runnable() {
			@Override
			public void run() {
				Message msg = new Message();
				// 此处判断主页是否存在，因为主页是通过loadUrl加载的，
				// 此时不会执行shouldOverrideUrlLoading进行页面是否存在的判断
				// 进入主页后，点主页里面的链接，链接到其他页面就一定会执行shouldOverrideUrlLoading方法了
				if (getRespStatus(url) == 404) {
					msg.what = 404;
				}
				handler.sendMessage(msg);
			}
		}).start();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private int getRespStatus(String url) {
		int status = -1;
		try {
			HttpHead head = new HttpHead(url);
			HttpClient client = new DefaultHttpClient();
			HttpResponse resp = client.execute(head);
			status = resp.getStatusLine().getStatusCode();
		} catch (IOException e) {
			status = 404;
		}
		return status;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.news_web_act_btn_goBack:
			finish();
			break;
		case R.id.news_web_act_btn_gouc:
			intentToSportteryFootball = new Intent();
			intentToSportteryFootball
					.setClass(
							NewsContent.this,
							com.esun.cheetah.view.personal.sportlotteryfootball.SportteryFootballAgp.class);
			bundleToSportteryFootbal = new Bundle();
			bundleToSportteryFootbal.putInt("CURRENT_TAB_NUM", 0);
			intentToSportteryFootball.putExtras(bundleToSportteryFootbal);
			EDebug.o(this, "click to shuangseqiu choose");
			startActivity(intentToSportteryFootball);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		this.unregisterReceiver(ConnectionChangeReceiver
				.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.registerReceiver(
				ConnectionChangeReceiver.getConnectionChangeReceiver(),
				ConnectionChangeReceiver.getIntentFilter());
	}

}
